﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Runtime.Caching;
using System.Web.Mvc;
using Controllerss;
using Core.Contract.DataContract;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using www.Controllerss;
using www.Core.Contract.DataContract;
using www.Models;
//using www.SService;

namespace www.Controllers
{
   
    [Authorize]
    public class AccountController : Controller
    {
        private readonly ObjectCache _cache = MemoryCache.Default;
        //private readonly HyServicesClient _service1 = new HyServicesClient();
        private readonly LoginController _loginController=new LoginController();
        private readonly MenuController _menuController=new MenuController();
        private readonly AdvertiseController _advertiseController=new AdvertiseController();
        private readonly VideoController _videoController=new VideoController();
        private readonly Utilities _utilities = new Utilities();

        #region Culture

        public void GetCulture(string cul = null)
        {
            if (cul == null && Session["Culture"] == null)
            {
                var languagecode = _utilities.GetLanguageCode();
                Session["LanguageCode"] = languagecode;
                Session["Culture"] = languagecode == 1 ? "vi-VN" : languagecode == 3 ? "zh-CN" : "en-US";
            }
            else
            {
                var culs = Convert.ToString(cul ?? Session["Culture"]);
                Session["LanguageCode"] = culs == "vi-VN" ? 1 : culs == "zh-CN" ? 3 : 2;
                Session["Culture"] = culs;
            }
        }
        #endregion
        #region Get info basic

        public void GetInfoBasic()
        {
            var lMenu = (List<RelaxMenuDataContract>)_cache["Menu"];
            var lAdvertise = (List<RelaxAdvertiseDataContract>)_cache["Advertise"];
            var lVideo = (List<RelaxVideoDataContract>)_cache["Video"];
            if (lMenu == null)
            {
                lMenu = _menuController.GetMenuDataContracts().ToList();
                if (lMenu.Any())
                {
                    var policy = new CacheItemPolicy();
                    policy.AbsoluteExpiration = DateTimeOffset.Now.AddHours(27);
                    _cache.Set("Menu", lMenu, policy);
                }
            }

            ViewBag.RelaxMenuDataContracts = lMenu.Where(p => p.Active == Constant.Active.Display && p.Type == 1 && p.Languagecode == Convert.ToInt32(Session["LanguageCode"])).ToList();
            if (lAdvertise == null)
            {
                lAdvertise = _advertiseController.GetAdvertiseDataContracts().ToList();
                if (lAdvertise.Any())
                {
                    var policy = new CacheItemPolicy();
                    policy.AbsoluteExpiration = DateTimeOffset.Now.AddHours(27);
                    _cache.Set("Advertise", lAdvertise, policy);
                }

            }

            var lAdvertises = lAdvertise.Where(p => p.Active == Constant.Active.Display && p.Languagecode == Convert.ToInt32(Session["LanguageCode"])).ToList();
           
            ViewBag.RelaxAdvertiseDataContracts = lAdvertises;

            if (lVideo == null)
            {
                lVideo = _videoController.GeVideoDataContracts().ToList();
                if (lVideo.Any())
                {
                    var policy = new CacheItemPolicy();
                    policy.AbsoluteExpiration = DateTimeOffset.Now.AddHours(27);
                    _cache.Set("Video", lVideo, policy);
                }
            }

            var lvideo = lVideo.Where(p => p.Active == Constant.Active.Display && p.Languagecode == Convert.ToInt32(Session["LanguageCode"])).OrderByDescending(o => o.Id).ToList();
           
            ViewBag.RelaxVideoDataContracts = lvideo.Skip(0).Take(6).ToList();

        }
        #endregion
       
       //  GET: /Account/Login
       [AllowAnonymous]
        public ActionResult Login()
        {
            try
            {
                GetCulture();
                GetInfoBasic();
                if (_cache["UserClient"] == null)
                {
                    var lData = _loginController.GetAllClientUser();
                    if (lData.Any())
                    {
                        var policy = new CacheItemPolicy {AbsoluteExpiration = DateTimeOffset.Now.AddHours(27)};
                        //ViewBag.Model = lData;
                        _cache.Set("UserClient", lData.ToList(), policy);
                    }
                }
            }
            catch (Exception)
            {
            }
            return View();
        }
        
        
       //  POST: /Account/LogOff

        [HttpPost]
        [AllowAnonymous]
        public ActionResult LogOff()
        {
            //WebSecurity.Logout();
            Session["Success"] = false;
            Session["Username"] = string.Empty;
            //Response.Redirect("~/Trang-chu.html");
            return RedirectToAction("Index", "Home");
        }

        //
        // POST: /Account/ExternalLogin

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public void ExternalLogin(string provider, string returnUrl)
        {
            try
            {
                OAuthWebSecurity.RequestAuthentication(provider, Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
                //return new ExternalLoginResult(provider, Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
            }
            catch (Exception)
            {
                RedirectToAction("Login", "Account");
            }
        }

        private  string GetPictureUrl(string faceBookId)
        {
            WebResponse response = null;
            var pictureUrl = string.Empty;
            try
            {
                var request = WebRequest.Create(string.Format("https://graph.facebook.com/{0}/picture", faceBookId));
                response = request.GetResponse();
                pictureUrl = response.ResponseUri.ToString();
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (response != null) response.Close();
            }
            return pictureUrl;
        }
      

        //
        // GET: /Account/ExternalLoginCallback

        [AllowAnonymous]
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            try
            {
                var result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));

                if (!result.IsSuccessful)
                {
                    return RedirectToAction("ExternalLoginFailure");
                }

                var check = false;

                if (_cache["UserClient"] != null)
                {
                    var lData = (List<RelaxLoginsDataContract>)_cache["UserClient"];
                    var checkexists = lData.FirstOrDefault(p => p.UserName == result.UserName);
                    if (checkexists != null)
                    {
                        Session["Success"] = true;
                        Session["Username"] = checkexists.Image;
                        Session["Alt"] = checkexists.MemberName;
                        Session["UserId"] = checkexists.Id;
                        check = true;
                    }
                    else
                    {
                        if (result.Provider.ToLower() == "google" || result.Provider.ToLower() == "linkedin" || result.Provider.ToLower() == "tiwitter")
                        {
                            var loginData = new RelaxLoginsDataContract
                            {
                                UserName = result.UserName,
                                MemberName = result.UserName,
                                Active = 1,
                                Email = result.UserName,
                                Birthday = DateTime.Now,//Convert.ToDateTime(result.ExtraData["birthday"]),
                                Role = 0
                            };
                            var resul = _loginController.Add(loginData);
                            if (Convert.ToInt32(resul) > 0)
                            {
                                loginData.Id = resul;
                                lData.Add(loginData);
                                _cache["UserClient"] = lData;
                                Session["Success"] = true;
                                Session["Username"] = null;
                                Session["UserId"] = resul;
                                Session["Alt"] = result.UserName;
                                check = true;
                            }
                            else
                            {
                                Session["Success"] = false;
                                Session["Username"] = string.Empty;
                            }
                        }
                        else if (result.Provider.ToLower() == "facebook")
                        {
                            var imageurl = GetPictureUrl(result.ExtraData["id"]);

                            var path = "Images/u/" + result.ExtraData["id"] + ".jpg";
                            using (var client = new WebClient())
                            {
                                client.DownloadFile(imageurl, Server.MapPath("~/" + path));
                            }

                            var loginData = new RelaxLoginsDataContract
                            {
                                UserName = result.UserName,
                                Gender = result.ExtraData["gender"] == "male" ? 1 : 0,
                                MemberName = result.ExtraData["name"],
                                Active = 1,
                                Email = result.UserName,
                                Birthday = DateTime.Now,//Convert.ToDateTime(result.ExtraData["birthday"]),
                                Password = result.ExtraData["id"],
                                Image = path,
                                Role = 0
                            };
                            var resul = _loginController.Add(loginData);
                            if (Convert.ToInt32(resul) > 0)
                            {
                                loginData.Id = resul;
                                lData.Add(loginData);
                                _cache["UserClient"] = lData;
                                Session["Success"] = true;
                                Session["Username"] = path;
                                Session["Alt"] = result.ExtraData["name"];
                                Session["UserId"] = resul;
                                check = true;
                            }
                            else
                            {
                                Session["Success"] = false;
                                Session["Username"] = string.Empty;
                            }
                        }
                        else if (result.Provider.ToLower() == "yahoo")
                        {
                            var loginData = new RelaxLoginsDataContract
                            {
                                UserName = result.UserName,
                                MemberName = result.ExtraData["fullName"],
                                Active = 1,
                                Email = result.UserName,
                                Birthday = DateTime.Now,//Convert.ToDateTime(result.ExtraData["birthday"]),
                                Role = 0
                            };
                            var resul = _loginController.Add(loginData);
                            if (Convert.ToInt32(resul) > 0)
                            {
                                loginData.Id = resul;
                                lData.Add(loginData);
                                _cache["UserClient"] = lData;
                                Session["Success"] = true;
                                Session["Username"] = null;
                                Session["Alt"] = result.UserName;
                                Session["UserId"] = resul;
                                check = true;
                            }
                            else
                            {
                                Session["Success"] = false;
                                Session["Username"] = string.Empty;
                            }
                        }
                    }
                }
                else
                {
                    if (result.Provider.ToLower() == "google" || result.Provider.ToLower() == "linkedin" || result.Provider.ToLower() == "tiwitter")
                    {
                        var loginData = new RelaxLoginsDataContract
                        {
                            UserName = result.UserName,
                            MemberName = result.UserName,
                            Email = result.UserName,
                            Active = 1,
                            Birthday = DateTime.Now,
                            Role = 0
                        };
                        var resul = _loginController.Add(loginData);
                        if (Convert.ToInt32(resul) > 0)
                        {
                            var lData = (List<RelaxLoginsDataContract>)_cache["UserClient"];
                            loginData.Id = resul;
                            if (lData == null)
                                lData = new List<RelaxLoginsDataContract>();
                            lData.Add(loginData);
                            _cache["UserClient"] = lData;
                            Session["Success"] = true;
                            Session["Username"] = null;
                            Session["Alt"] = result.UserName;
                            Session["UserId"] = resul;
                            check = true;
                        }
                        else
                        {
                            Session["Success"] = false;
                            Session["Username"] = string.Empty;
                        }
                    }
                    else if (result.Provider.ToLower() == "facebook")
                    {
                        var imageurl = GetPictureUrl(result.ExtraData["id"]);

                        var path = "Images/u/" + result.ExtraData["id"] + ".jpg";
                        using (var client = new WebClient())
                        {
                            client.DownloadFile(imageurl, Server.MapPath("~/" + path));
                        }

                        var loginData = new RelaxLoginsDataContract
                        {
                            UserName = result.UserName,
                            Gender = result.ExtraData["gender"] == "male" ? 1 : 0,
                            MemberName = result.ExtraData["name"],
                            Email = result.UserName,
                            Active = 1,
                            Birthday = DateTime.Now,//Convert.ToDateTime(result.ExtraData["birthday"]),
                            Password = result.ExtraData["id"],
                            Image = path,
                            Role = 0,
                        };
                        var resul = _loginController.Add(loginData);
                        if (Convert.ToInt32(resul) > 0)
                        {
                            var lData = (List<RelaxLoginsDataContract>)_cache["UserClient"];
                            loginData.Id = resul;
                            if (lData == null)
                                lData = new List<RelaxLoginsDataContract>();
                            lData.Add(loginData);
                            _cache["UserClient"] = lData;
                            Session["Success"] = true;
                            Session["Username"] = path;
                            Session["Alt"] = result.ExtraData["name"];
                            Session["UserId"] = resul;
                            check = true;
                        }
                        else
                        {
                            Session["Success"] = false;
                            Session["Username"] = string.Empty;
                        }
                    }
                    else if (result.Provider.ToLower() == "yahoo")
                    {
                        var loginData = new RelaxLoginsDataContract
                        {
                            UserName = result.UserName,
                            MemberName = result.ExtraData["fullName"],
                            Active = 1,
                            Email = result.UserName,
                            Birthday = DateTime.Now,//Convert.ToDateTime(result.ExtraData["birthday"]),
                            Role = 0
                        };
                        var resul = _loginController.Add(loginData);
                        if (Convert.ToInt32(resul) > 0)
                        {
                            var lData = (List<RelaxLoginsDataContract>)_cache["UserClient"];
                            loginData.Id = resul;
                            if (lData == null)
                                lData = new List<RelaxLoginsDataContract>();
                            lData.Add(loginData);
                            _cache["UserClient"] = lData;
                            Session["Success"] = true;
                            Session["Username"] = null;
                            Session["Alt"] = result.UserName;
                            Session["UserId"] = resul;
                            check = true;
                        }
                        else
                        {
                            Session["Success"] = false;
                            Session["Username"] = string.Empty;
                        }
                    }
                }
                if (check)
                {
                    if (Session["check"] != null)
                    {
                        switch (Convert.ToInt32(Session["check"]))
                        {
                            case 1:
                                return RedirectToAction("PostImage", "Home");
                            case 2:
                                return RedirectToAction("PostVideo", "Home");
                            case 3:
                                return RedirectToAction("PostStory", "Home");
                            case 4:
                                return RedirectToAction("PostAngleSaid", "Home");
                            case 5:
                                return RedirectToAction("PostNews", "Home");
                            case 6:
                                return RedirectToAction("Ragecomic", "Home");
                            case 7:
                                return RedirectToAction("Meme", "Home");
                        }
                    }
                    else
                        return RedirectToAction("Post", "Home");

                }
            }
            catch (Exception)
            {
                return RedirectToAction("Login", "Account");
            }


            return RedirectToAction("Login", "Account");
        }


        
         //GET: /Account/ExternalLoginFailure

        [AllowAnonymous]
        public ActionResult ExternalLoginFailure()
        {
            try
            {
                GetCulture();
                GetInfoBasic();
            }
            catch (Exception)
            {

            }
            return View();
        }

        [AllowAnonymous]
        [ChildActionOnly]
        public ActionResult ExternalLoginsList(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return PartialView("_ExternalLoginsListPartial", OAuthWebSecurity.RegisteredClientData);
        }

        [ChildActionOnly]
        public ActionResult RemoveExternalLogins()
        {
            var accounts = OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name);
            var externalLogins = (from account in accounts
                let clientData = OAuthWebSecurity.GetOAuthClientData(account.Provider)
                select new ExternalLogin
                {
                    Provider = account.Provider, ProviderDisplayName = clientData.DisplayName, ProviderUserId = account.ProviderUserId,
                }).ToList();

            ViewBag.ShowRemoveButton = externalLogins.Count > 1 || OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name));
            return PartialView("_RemoveExternalLoginsPartial", externalLogins);
        }

        #region Helpers
       
        public enum ManageMessageId
        {
            ChangePasswordSuccess,
            SetPasswordSuccess,
            RemoveLoginSuccess,
        }

        internal class ExternalLoginResult : ActionResult
        {
            public ExternalLoginResult(string provider, string returnUrl)
            {
                Provider = provider;
                ReturnUrl = returnUrl;
            }
           
            public string Provider { get; private set; }
            public string ReturnUrl { get; private set; }
          
            public override void ExecuteResult(ControllerContext context)
            {
                try
                {
                    OAuthWebSecurity.RequestAuthentication(Provider, ReturnUrl);
                }
                catch (Exception)
                {
                    
                }
            }
        }
        
        #endregion
    }
}
